package businessServlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.google.appengine.api.datastore.Text;
import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array;

import controller.Controller;

@SuppressWarnings("serial")
public class SendMessageBusiness extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
	}
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

		try{			
		
			String userName = (String) req.getSession().getAttribute("userNameBusiness");
			int orderID = Integer.parseInt(req.getParameter("orderID"));
			Controller controller = Controller.getInstance();
			ArrayList<String> listOfMessages = controller.getBiz(userName).getMessages();
			Integer index = 0;
			String message = "";
			String messageId = req.getParameter("message");
			for (String mes:listOfMessages){
				if (index.toString().equals(messageId)){
					message = mes;
					break;
				}
			index++;
			}

			//String message = req.getParameter("message");
			System.out.println("the message = "+message);
			int result = controller.sendMessage(userName, orderID, new Text(message));
			
			switch (result)
			{
			case 0:
				System.out.println("send message business");
				req.getSession().removeAttribute("validErrorBiz");
				resp.sendRedirect("allOrders.jsp");
				break;
			case 1:
				req.getSession().setAttribute("validErrorBiz","order id not exist");	
				resp.sendRedirect("home.jsp");
				break;				
			}			
			
		}
		catch(NumberFormatException e)
		{
			req.getSession().setAttribute("validErrorBiz","order id is not a number");	
			resp.sendRedirect("home.jsp");
			
		}
		
		

	}
}
